package org.example.elmfront.controller;
import org.example.elmfront.entity.OrderItem;
import org.example.elmfront.service.OrderItemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
@RestController
@RequestMapping("/order-items")
public class OrderItemController {

    @Autowired
    private OrderItemService orderItemService;

    // 增加订单项
    @PostMapping("/add")
    public ResponseEntity<String> addOrderItem(@RequestBody OrderItem orderItem) {
        try {
            orderItemService.addOrderItem(orderItem);
            return ResponseEntity.ok("Order item added successfully");
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Failed to add order item");
        }
    }

    // 删除订单项
    @DeleteMapping("/delete/{id}")
    public ResponseEntity<String> deleteOrderItem(@PathVariable Integer id) {
        try {
            orderItemService.deleteOrderItem(id);
            return ResponseEntity.ok("Order item deleted successfully");
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Failed to delete order item");
        }
    }

    // 更新订单项
    @PutMapping("/update")
    public ResponseEntity<String> updateOrderItem(@RequestBody OrderItem orderItem) {
        try {
            orderItemService.updateOrderItem(orderItem);
            return ResponseEntity.ok("Order item updated successfully");
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Failed to update order item");
        }
    }

    // 查询某个订单的所有订单项
    @GetMapping("/order/{orderId}")
    public ResponseEntity<List<OrderItem>> getOrderItems(@PathVariable Long orderId) {
        List<OrderItem> orderItems = orderItemService.getOrderItemsByOrderId(orderId);
        return ResponseEntity.ok(orderItems);
    }

    // 根据 ID 查询订单项
    @GetMapping("/{id}")
    public ResponseEntity<OrderItem> getOrderItemById(@PathVariable Integer id) {
        OrderItem orderItem = orderItemService.getOrderItemById(id);
        if (orderItem != null) {
            return ResponseEntity.ok(orderItem);
        } else {
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body(null);
        }
    }
}

